/**
 * DataGrid 组件
 * @description 基于laytpl 、laypage、layer 封装的组件
 * @author wangy
 * @link 
 * @license MIT
 * @version 1.0.1
 */
layui.define(['layer', 'laypage', 'laytpl','form'], function(exports) {
    "use strict";
    var $ = layui.jquery,
        layer = parent.layui.layer === undefined ? layui.layer : parent.layui.layer,
        form = layui.form(),
        laytpl = layui.laytpl;

    var DataGrid = function() {
        this.config = {
            url: undefined, //数据远程地址
            type: 'POST', //数据的获取方式  get or post
            elem: undefined, //内容容器
            params: {}, //获取数据时传递的额外参数
            openWait: false, //加载数据时是否显示等待框 
            tempElem: undefined, //模板容器
            rowBtnClickEvent: undefined,//每一行last-children按钮点击事件
            rowEditEvent:false,
            sortName:undefined,
            sortOrder:'asc',
            tempType: 0,
            paged: true,
            pageConfig: { //参数应该为object类型
                elem: undefined,
                pageSize: 15 //分页大小
            },
            success: undefined, //type:function
            fail: undefined, //type:function
            complate: undefined, //type:function
            serverError: function(xhr, status, error) { //ajax的服务错误
                throwError("错误提示： " + xhr.status + " " + xhr.statusText);
            }
        };
    };
    /**
     * 版本号
     */
    DataGrid.prototype.v = '1.0.0';

    /**
     * 设置
     * @param {Object} options
     */
    DataGrid.prototype.set = function(options) {
        var that = this;
        $.extend(true, that.config, options);
        return that;
    };
    
    /**
     * 初始化
     * @param {Object} options
     */
    DataGrid.prototype.init = function(options) {
        var that = this;
        $.extend(true, that.config, options);
        var _config = that.config;
        if(_config.url === undefined) {
            throwError('Paging Error:请配置远程URL!');
        }
        if(_config.elem === undefined) {
            throwError('Paging Error:请配置参数elem!');
        }
        if($(_config.elem).length === 0) {
            throwError('Paging Error:找不到配置的容器elem!');
        }
        if(_config.tempType === 0) {
            if(_config.tempElem === undefined) {
                throwError('Paging Error:请配置参数tempElem!');
            }
            if($(_config.tempElem).length === 0) {
                throwError('Paging Error:找不到配置的容器tempElem!');
            }
        }
        if(_config.paged) {
            var _pageConfig = _config.pageConfig;
            if(_pageConfig.elem === undefined) {
                throwError('Paging Error:请配置参数pageConfig.elem!');
            }
        }
        if(_config.type.toUpperCase() !== 'GET' && _config.type.toUpperCase() !== 'POST') {
            throwError('Paging Error:type参数配置出错，只支持GET或都POST');
        }
        that.get({
            pageIndex: 1,
            pageSize: _config.pageConfig.pageSize
        });

        return that;
    };
    
    /**
     * 复选框全选和反选
     * @param {Object} options
     */
    DataGrid.prototype.render = function(params) {
        var that = this;
        $.extend(true, that.config, params);
        var _config = that.config;
        form.on(params, function(data) {
                    var elem = data.elem;
                   $(_config.elem).children('tr').each(function() {
                    var $that = $(this);
                        //全选或反选
                    $that.children('td').eq(0).children('input[type=checkbox]')[0].checked = elem.checked;
                    form.render('checkbox');
                });
            });//渲染checkbox结束
        return that;
    };
    
    /**
     * 获取选中的checkbox，返回值:选中行的行数据、行索引、数据id
     * 给td标签class="primary-key"属性，指定该数据为整行数据的Id
     */
    DataGrid.prototype.getCheckedRows = function(param) {
        var that = this;
        var chk_value = [];//行数据
        var rowIndex = [];//行索引
        var ids = [];//由开发者指定主键id
        var result = new Object;
        $.extend(true, that.config, param);
        var _config = that.config;
        $(_config.elem).children('tr').each(function() {
                var $that = $(this);
                var st=$that.children('td').eq(0).children('input[type=checkbox]')[0].checked;
                if(st){
                    rowIndex.push($that.index());
                    $that.find('td').each(function(n,value){
                        if(value.className == "primary-key"){
                            ids.push($(this).text());
                        }
                        if(value.className != "datagrid-disable"){
                            chk_value.push($(this).text());
                            
                        }
                    });
                    result[$that.index()] = chk_value;
                    chk_value = [];
                    result.rowIndex = rowIndex;//返回被选中的行索引
                    result.id = ids;//返回被选中数据的id
                }
                
        });
        return result;
    };
    
    //获取一行数据
    DataGrid.prototype.getRow = function(param) {
        var that = this;
        var chk_value = [];//行数据
        var result = new Object;
        $.extend(true, that.config, param);
        var _config = that.config;
        var rowIndex=param.parent('td').parent("tr").index();
        $(_config.elem).children('tr').eq(rowIndex).find('td').each(function(n,value){
            if(value.className != "datagrid-disable"){
                chk_value.push($(this).text());
                result = chk_value;
            }
            if(value.className == "primary-key"){
                result.id = $(this).text();
            }
            result.rowIndex = rowIndex;
        });
        return result;
    };
    
    //获取table里的数据
    DataGrid.prototype.getTable = function(param) {
        var that = this;
        var chk_value = [];//行数据
        var result = {};
        $.extend(true, that.config, param);
        var _config = that.config;
        $(_config.elem).children('tr').each(function(){
            var $that = $(this);
            $that.find('td').each(function(n,value){
                if(value.className != "datagrid-disable"){
                    chk_value.push($(this).text());
                }
            });
            result[$that.index()] = chk_value;
            chk_value = [];
            
        });
        return result;
    };
    
    //加载
    DataGrid.prototype.load = function(param){
        var that = this;
        $.extend(true, that.config, param);
        //alert(param.startTime);
        var _config = that.config;
        var params = $(param).serialize();
        
        $.ajax({
            type:"POST",
            url:_config.url+"?"+params,
            data:{sortName:_config.sortName,sortOrder:_config.sortOrder},
            async:true,
            success:function(){
                that.get({
                });
            }
        });
    }
    
    /*
     * 序列化form表单里的值
     * 参数：form的id
     * 返回值：Object
     */
    DataGrid.prototype.serializeObject = function(options){
        var formValues = $(options).serialize();  
        formValues = formValues.replace(/\+/g," ");// g表示对整个字符串中符合条件的都进行替换
        var jsonObj = {};
        var param = formValues.split("&");  
        for ( var i = 0; param != null && i < param.length; i++) {  
            var para = param[i].split("=");  
            jsonObj[para[0]] = para[1];  
        }
        var temp = JSON.stringify(jsonObj);  
        var queryParam = JSON.parse(temp);
        return queryParam;
    }
    
    /**
     * 获取数据
     * @param {Object} options
     */
    DataGrid.prototype.get = function(options) {
        var that = this;
        var _config = that.config;
        var loadIndex = undefined;
        if(_config.openWait) {
            loadIndex = layer.load(2);
        }
        if(_config.sortName != undefined){
            _config.params.sortName = _config.sortName;
            _config.params.sortOrder = _config.sortOrder;
        }
        //默认参数
        var df = {
            pageIndex: 1,
            pageSize: _config.pageConfig.pageSize
        };
        $.extend(true, _config.params, df, options);
        $.ajax({
            type: _config.type,
            url: _config.url,
            data: _config.params,
            dataType: 'json',
            success: function(result, status, xhr) {
                
                if(result.code === 0) {
                    //获取模板
                    var tpl = _config.tempType === 0 ? $(_config.tempElem).html(): _config.tempElem;
                    //渲染数据
                    laytpl(tpl).render(result, function(html) {
                        $(_config.elem).html(html);
                    });
                    
                    //排序
                    //TODO 添加检索参数
                    if(_config.sortName){
                        $(_config.elem).parent("table").children('thead').children("tr").find("th").each(function(n,value){
                            var $that = $(this);
                                $that.unbind('click');
                                $that.on('click',function(){
                                    if ($that.attr("sortable") != "true") return;
                                    var order = _config.sortOrder;
                                    if(_config.sortOrder == "asc"){
                                        order = "desc";
                                    }else{
                                        order = "asc";
                                    }
                                    var field = $that.attr("field");
                                    delete(_config.sortName);
                                    delete(_config.sortOrder);
                                    _config.sortName = field;
                                    _config.sortOrder = order;
                                    alert(field);
                                    that.get({});
                                });
                        });
                    }
                    
                    //绑定每一行last-children 按钮的点击事件
                    if(_config.rowBtnClickEvent!=null){
                        $(_config.elem).children('tr').each(function() {
                            var $that = $(this);
                            var aClickEvent=_config.rowBtnClickEvent;
                            for (var i = 0;i < aClickEvent.length;i++) {
                                var dataOpt = "a[data-opt="+aClickEvent[i].name+"]";
                                $that.children('td:last-child').children(dataOpt).on('click',aClickEvent[i].opt);
                            }
                        });
                    }
                    //行编辑
                    if(_config.rowEditEvent.edit){
                            $(function(){ 
                            //找到所有的td节点 
                            var tds=$(_config.elem).children('tr').children('td');
                            //给所有的td添加点击事件 
                            tds.click(function(){ 
                                //获得当前点击的对象 
                                var td=$(this);
                                //取出当前td的文本内容保存起来 
                                var arr = td.trigger("focus").trigger("select");
                                $.each(arr,function(n,value) { 
                                    if(value.className == "datagrid-disable"){
                                        return;
                                    }else{
                                        var oldText=td.text(); 
                                        //建立一个文本框，设置文本框的值为保存的值    
                                        var input=$("<input type='text' value='"+oldText+"'/>");  
                                        //将当前td对象内容设置为input 
                                        td.html(input); 
                                        //设置文本框的点击事件失效 
                                        input.click(function(){ 
                                            return false; 
                                        }); 
                                        //设置文本框的样式 
                                        input.css("border-width","0");               
                                        input.css("font-size","16px"); 
                                        input.css("text-align","left");
                                        input.css("background-color","#F7F7F7").css("height","20px");
                                        //设置文本框宽度等于td的宽度 
                                        input.width(td.width()); 
                                        //当文本框得到焦点时触发全选事件   
                                        input.trigger("focus").trigger("select");  
                                        //当文本框失去焦点时重新变为文本 
                                        input.blur(function(){ 
                                        var input_blur=$(this); 
                                        //保存当前文本框的内容 
                                        var newText=input_blur.val();  
                                        td.html(newText);  
                                        });
                                        //响应键盘事件 
                                        input.keyup(function(event){ 
                                        // 获取键值 
                                            var keyEvent=event || window.event; 
                                            var key=keyEvent.keyCode; 
                                            //获得当前对象 
                                            var input_blur=$(this); 
                                            switch(key) 
                                            { 
                                                case 13://按下回车键，保存当前文本框的内容
                                                    var newText=input_blur.val();  
                                                    td.html(newText);
                                                    if (_config.rowEditEvent.url != null || _config.rowEditEvent.url != "") {
                                                        var row = datagrid.getTable();
                                                        $.ajax({
                                                            url:_config.rowEditEvent.url,
                                                            data:row.rowData,
                                                            success:function(obj){
                                                                layer.msg(obj.msg);
                                                                location.reload();
                                                            }
                                                        });
                                                    }
                                                    break; 
                                                case 27://按下esc键，取消修改，把文本框变成文本 
                                                    td.html(oldText);  
                                                    break; 
                                            } 
                                        });
                                    }//else结束
                                });
                            }); 
                        });
                    }
                    if(_config.paged) {
                        if(result.total === null || result.total === 0) {
                            throwError('Paging Error:请返回数据总数！');
                            return;
                        }
                        var _pageConfig = _config.pageConfig;
                        var pageSize = _pageConfig.pageSize;
                        var pages = result.total % pageSize == 0 ?
                            (result.total / pageSize) : (result.total / pageSize + 1);

                        var defaults = {
                            cont: $(_pageConfig.elem),
                            curr: _config.params.pageIndex,
                            pages: pages,
                            jump: function(obj, first) {
                                //得到了当前页，用于向服务端请求对应数据
                                var curr = obj.curr;
                                if(!first) {
                                    that.get({
                                        pageIndex: curr,
                                        pageSize: pageSize
                                    });
                                }
                            }
                        };
                        $.extend(defaults, _pageConfig); //参数合并
                        layui.laypage(defaults);
                    }
                    if(_config.success) {
                        _config.success(); //渲染成功
                    }
                } else {
                    if(_config.fail) {
                        _config.fail(result.msg); //获取数据失败
                    }
                }
                if(_config.complate) {
                    _config.complate(); //渲染完成
                }
                if(loadIndex !== undefined)
                    layer.close(loadIndex); //关闭等待层
            },
            error: function(xhr, status, error) {
                if(loadIndex !== undefined)
                    layer.close(loadIndex); //关闭等待层
                _config.serverError(xhr, status, error); //服务器错误
            }
        });
    };
    /**
     * 抛出一个异常错误信息
     * @param {String} msg
     */
    function throwError(msg) {
        throw new Error(msg);
    };

    var datagrid = new DataGrid();
    exports('datagrid', function(options) {
        return datagrid.set(options);
    });
});